package cn.lysj.framework.store.service;

import cn.lysj.framework.base.BaseService;
import cn.lysj.framework.common.CommonConstant;
import cn.lysj.framework.common.domain.User;
import cn.lysj.framework.common.repository.UserRepository;
import cn.lysj.framework.common.utils.web.ParamUtil;
import cn.lysj.framework.common.utils.web.Resp;
import cn.lysj.framework.store.domain.Store;
import cn.lysj.framework.store.repository.StoreRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;

/**
 * @author drj
 * @description 门店服务层
 * @create 2018-10-29 10:02:38
 **/
@Slf4j
@Service
@Transactional
public class StoreService implements BaseService<Store> {

    @Resource
    private StoreRepository storeRepository;
    @Resource
    private UserRepository userRepository;

    @Override
    public StoreRepository getRepository() {
        return storeRepository;
    }

    public Store findByUserId(String id){
        if(ParamUtil.isBlank(id)){
            return null;
        }
        return storeRepository.findByUserIdAndDelFlag(id,CommonConstant.NORMAL_FLAG);
    };

    public Resp save(User user,Store store){
        if(storeRepository.findByUserIdAndDelFlag(user.getId(),CommonConstant.NORMAL_FLAG)!=null){
            return new Resp(Resp.PARAM_ERROR,"添加失败!您已经拥有门店,请勿再次添加");
        };
        store.setUserId(user.getId());
        store = storeRepository.save(store);
        user.setStoreId(store.getId());
        userRepository.save(user);
        return new Resp("添加门店成功!");
    }
    /**
     * @author ZhangWenJian
     * @date 2019/2/22 10:00
     * @title isDoBusiness
     * @param time
     * @return java.lang.Boolean
     * @description 根据所传入时间段 hh：mm 判断当前是否处于某时间端
     */
    public Boolean isDoBusiness(String time[]){
        String beginTime[] = time[0].split(":");
        String endTime[] = time[1].split(":");
        long beginDate = getTime(beginTime);
        long endDate = getTime(endTime);
        if(new Date().getTime() >= beginDate && new Date().getTime() <= endDate){
            return true;
        }
        else{
            return false;
        }
    }

    public long getTime(String time[]){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time[0]));
        calendar.set(Calendar. MINUTE, Integer.parseInt(time[1]));
        calendar.set(Calendar. SECOND, 0);
        calendar.set(Calendar. MILLISECOND,0);
        return calendar.getTime().getTime();
    }
}
